<?php

namespace app\api\model;

use app\api\model\VolleyDesc as Balance;
use GatewayClient\Gateway;
use think\Cache;
use think\Log;
use think\Db;

class Task extends Common
{
    static public function finish($task, $user_id, $value='',$channel = 1)
    {
        $task = self::get(['name' => $task, 'is_hidden' => 0, 'channel'=>$channel]);

        if (!$task) {
            return false;
        }

        $user = User::get($user_id);
        if ($user['reg']!=1) return false;
        if ($task['sex_limit'] != 0) {
            $sexlimit = ['','女','男'];
            if ($sexlimit[$task['sex_limit']] != $user['sex']) {
                return false;
            }
        }

        $userTask = UserTask::get(['task' => $task['name'], 'user_id' => $user_id,'channel'=>$channel]);

        if ($task['types'] == 1 && $userTask) {
            return false;
        }

        if ($task['value'] && $task['value'] > $value) {
            return false;
        }

        if ($task['types'] == 2 && $task['max']) {
            //$cost = Balance::where(['user_id' => $user_id, 'content' => '[完成任务] ' . $task['title']])->whereTime('time', 'd')->sum('price');
            $cost = Db::name('task_daily')->master()->where(['user_id' => $user_id, 'name' => $task['name'],'channel'=>$channel])->whereTime('create_time', 'd')->sum('reward');

            if (($cost + $task['reward']) > $task['max']) {
                return false;
            }
        }

        UserTask::create(['task' => $task['name'], 'user_id' => $user_id, 'create_time' => time(),'channel'=>$channel]);
    
        try {
            Cache::rm('userTask' . $user_id);
        } catch (\Exception $e) {
            Log::write('userTask-'.$e->getMessage().'-100021', 'error');
        }
        if ($task['name'] == 'app_score') {
            return;
        }
        if ($task['reward'] + 0) {
            if ($task['reward_type']) {
                YaoqingRecords::index($user_id, 0, $task['reward'], '[完成任务] ' . $task['title'], 1);
            } else if ($user['sex'] == '女') {
                Balance::beans($user_id, $task['reward'], '[完成任务] ' . $task['title'], 1);
            } else {
                Balance::index($user_id, $task['reward'], '[完成任务] ' . $task['title'], 1);
            }
    
            if ($task['types'] == 2 && $task['max']) {
                self::updateTaskDaily($user_id, $task['name'], $task['reward'], $channel);
            }
            
            $message = json_encode([
                "code" => 200,
                "action" => 'model/task/finish',
                'data' => [
                    "title" => $task['title'] . '奖励红包',
                    "money" => $task['reward'],
                    "money_type" => $task['reward_type'],
                    'msg' => '已存入您的账户，可提现哦~'
                ]
            ], JSON_UNESCAPED_UNICODE);

            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user_id, $message);
        }
    }
    
    static public function updateTaskDaily($user_id, $task, $reward, $channel = 1)
    {
        if ($reward > 0) {
            $taskDaily = TaskDaily::get(['user_id' => $user_id, 'name' => $task, 'channel' => $channel]);
            if ($taskDaily) {
                $today_start = strtotime(date('Y-m-d'));

                if (strtotime($taskDaily['create_time']) < $today_start) {
                    TaskDaily::update([
                        'id' => $taskDaily['id'],
                        'reward' => $reward,
                        'create_time' => time(),
                    ]);
                } else {
                    TaskDaily::update([
                        'id' => $taskDaily['id'],
                        'reward' => $reward + $taskDaily['reward'],
                        'create_time' => time(),
                    ]);
                }
            } else {
                TaskDaily::create([
                    'user_id' => $user_id,
                    'name' => $task,
                    'reward' => $reward,
                    'create_time' => time(),
                    'channel'   =>  $channel
                ]);
            }
        }
    }
}
